package com.uzhie.spring;

import com.google.common.base.Strings;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 跨域过滤器
 *
 * @author TangFei
 *         <p>
 *         Created by TangFei on 2018/3/28.
 *         </p>
 * @since jdk
 */
public class HttpCrossFilter implements Filter {

    private Logger logger = Logger.getLogger(this.getClass());

    private String allowOrigin;
    private String allowMethods;
    private String allowCredentials;
    private String allowHeaders;
    private String exposeHeaders;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        allowOrigin = filterConfig.getInitParameter("allowOrigin");
        allowMethods = filterConfig.getInitParameter("allowMethods");
        allowCredentials = filterConfig.getInitParameter("allowCredentials");
        allowHeaders = filterConfig.getInitParameter("allowHeaders");
        exposeHeaders = filterConfig.getInitParameter("exposeHeaders");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        logger.trace("enter HttpCrossFilter method doFilter");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if (!Strings.isNullOrEmpty(allowOrigin)) {
            String[] origins = allowOrigin.split(",");
            String originHeader = request.getHeader("Origin");
            if (Arrays.asList(origins).contains(originHeader) || Arrays.asList(origins).contains("*")) {
                response.setHeader("Access-Control-Allow-Origin", originHeader);
            } else {
                response.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
        if (!Strings.isNullOrEmpty(allowMethods)) {
            response.setHeader("Access-Control-Allow-Methods", allowMethods);
        }
        if (!Strings.isNullOrEmpty(allowCredentials)) {
            response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
        }
        if (!Strings.isNullOrEmpty(allowHeaders)) {
            response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        }
        if (!Strings.isNullOrEmpty(exposeHeaders)) {
            response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
        }
        chain.doFilter(req, res);
        response.setHeader("Content-Type", "application/json");
    }

    @Override
    public void destroy() {
        logger.trace("enter HttpCrossFilter method destroy");
    }
}
